<template>
	<view class="container">
		<uni-forms ref="baseForm" :modelValue="baseFormData">
			<uni-forms-item labelWidth="90px" class="form_item" label="商品分类" required name="typeid">
				<uni-data-select v-model="baseFormData.typeid" :localdata="typeList" :clear="false">
				</uni-data-select>
			</uni-forms-item>
			<uni-forms-item labelWidth="90px" label="商品名称" required name="title">
				<uni-easyinput v-model="baseFormData.title" placeholder="商品名称" />
			</uni-forms-item>
			<uni-forms-item labelWidth="90px" label="商品价格" required name="price">
				<uni-easyinput v-model="baseFormData.price" placeholder="商品价格" />
			</uni-forms-item>
			<uni-forms-item labelWidth="90px" label="商品排序" name="displayorder">
				<uni-easyinput v-model="baseFormData.displayorder" placeholder="商品价格" />
			</uni-forms-item>
			<uni-forms-item labelWidth="90px" label="商品标签" name="labels">
				<view class="list_item" style="padding-bottom: 20upx;" v-for="(item,idx) in baseFormData.labels"
					:key="key[idx]">
					<view class="" style="display: flex;align-items: center;padding-bottom: 10upx;">
						<text>标签（{{idx-0+1}}）：</text><button size="mini" @click="deleteTap(idx)">删除</button>
					</view>
					<uni-easyinput :clearable="false" v-model="baseFormData.labels[idx]" placeholder="商品标签" />
				</view>
				<view class="">
					<button size="mini" @click="addLaber">添加商品标签</button>
				</view>
			</uni-forms-item>
			<uni-forms-item labelWidth="90px" class="form_item" label="上传图片" required name="img">
				<view class="f_imgs">
					<view class="f_img" v-if="baseFormData.img.length>0">
						<image :src="baseFormData.img" @click="previewImg(0,baseFormData.img)"></image>
						<text @click="deleteImg(index,1)">×</text>
					</view>
					<view class="f_img" v-else @click="selectGallery(1)">
						<image class="reaname_thumb_upload" src="/static/shizi.jpg" mode=""></image>
					</view>
				</view>
			</uni-forms-item>
			<view class="buttons">
				<button v-if="id!=-1" class="go_submit" type="primary" style="background-color: red;"
					@click="deleteShop">删除</button>
				<button class="go_submit" type="primary" @click="submit('baseForm')">提交</button>
				<button v-if="id!=-1" class="go_submit" type="primary" style="background-color: #4399fc;"
					@click="down">下架</button>
				<button v-if="id!=-1" class="go_submit" type="primary" style="background-color: #f0ad4e;"
					@click="goodsUp">上架</button>
			</view>

		</uni-forms>
		<uni-drawer ref="showRight" mode="left" :width="320" :mask-click="false">
			<gallery-list @changeImg="changeImg" :isMultiple="isMultiple" :uid="uid"></gallery-list>
		</uni-drawer>
		<view class="fill" v-show="isShow">
			<view class="fill_item">
				<bt-cropper ref="cropper" :ratio="ratio" :imageSrc="imageSrc"></bt-cropper>
				<button @click="crop">确定</button>
			</view>
		</view>
	</view>
</template>


<script>
	import galleryList from '@/components/galleryList.vue'
	import {
		v4
	} from 'uuid'
	import {
		mapState
	} from 'vuex'
	export default {
		computed: {
			...mapState(["url"])
		},
		components: {
			galleryList
		},
		data() {
			return {
				isCut: false,//是否裁剪
				showGallery: false,//是否显示图库
				isMultiple: false,//是否多选 
				isShow: false,
				ratio: 16/9,
				imageSrc: '',
				id: -1,
				uid: '',
				baseFormData: {
					id: '',
					title: '',
					price: '',
					typeid: '',
					img: [],
					labels: [],
					displayorder: '9999',
				},
				typeList: [],
				key: [],
				rules: {
					title: {
						rules: [{
							required: true,
							errorMessage: '请填写商品名',
						}]
					},
					price: {
						rules: [{
							required: true,
							errorMessage: '请填写价格',
						}]
					},
					typeid: {
						rules: [{
							required: true,
							errorMessage: '请选择分类',
						}]
					},
					img: {
						rules: [{
							required: true,
							format: 'object',
							errorMessage: '请上传商品图片',
						}]
					},
				}
			}
		},
		onReady() {
			this.$refs.baseForm.setRules(this.rules)
		},
		onLoad(option) {
			this.id = option.id ? option.id : this.id;
			this.uid = option.uid;
			this.getTypeList();
		},
		methods: {
			// 选择图片弹窗
			selectGallery(type){
				this.isCut = type;
				if(type==3){
					this.isMultiple = true;
				}else{
					this.isMultiple = false;
					if(type==1){
						this.ratio = 1/1;
					}else{
						this.ratio = 16/9;
					}
				}
				uni.showActionSheet({
					itemList: ['上传图片', '门店图库'],
					success: res=> {
						if(res.tapIndex == 0){//上传图片
							if(type==3){
								this.uplaodThumb(type,9)// 多选
							}else{
								this.uplaodThumb(type,1)// 单选
							}
						}else if(res.tapIndex == 1){//门店图库
							this.$refs['showRight'].open()
						}
					},
				});
			},
			// 裁剪弹框
			showCut(url){
				let that = this;
				that.imageSrc = url;
				that.isShow = true;
			},
			// 裁剪确认
			crop(){
			    // 通过组件定义的ref调用cropper方法，返回一个promise对象
			    this.$refs.cropper.crop().then((res)=>{
					this.realUpload(res,this.isCut);
			    })
			},
			// 图库选择图片
			changeImg(arr, type){
				// this.baseFormData.content = [...this.baseFormData.content,...arr];
				this.$refs['showRight'].close()
				console.log(arr)
				if(arr.length>0){
					if(this.isCut==1){
						this.showCut(arr);
					}
				}
			},
			// 选择图片
			uplaodThumb(type,count) {
				uni.chooseImage({
					count: count,
					success:res=>{
						var path = res.tempFilePaths;
						path.forEach((image)=>{
							if(type==3){
								this.realUpload(image,type);
							}else{
								this.showCut(image);
							}
						})
					}
				})
			},
			// 上传服务器
			realUpload(image,type){
				let token = uni.getStorageSync('token');
				var that = this;
				let arr = '';
				uni.showLoading({
					title: '上传中,请稍后'
				});
				uni.uploadFile({
					url: that.$url.state.url.upload,
					filePath: image,
					name: 'a',
					header: {
						token: token
					},
					formData: {
						'file': 'a'
					},
					success: upres => {
						let data = JSON.parse(upres.data);
						if (data.code == 200) {
							arr = data.data.url;
							if (type == 1) that.baseFormData.img = arr;
							// if (type == 2) that.baseFormData.thumb_url.push(arr);
							// if (type == 3) that.baseFormData.content.push(arr);;
							uni.hideLoading();
							that.isShow = false;
						}
					},
					fail() {
						setTimeout(() => {
							that.$api.msg('上传失败，请重试')
						}, 100)
					},
				})
			},
			// 预览图片
			previewImg(idx,arr){
				if(typeof arr === 'string'){
					let arrs = [];
					arrs.push(arr);
					arr = arrs;
				}
				uni.previewImage({
					current: idx,
					urls: arr
				})
			},
			// 删除图片
			deleteImg(e, type) {
				if (type == 1) this.baseFormData.img = {};
				// if (type == 2) this.baseFormData.thumb_url.splice(e, 1);
				// if (type == 3) this.baseFormData.content.splice(e, 1);
			},
			deleteShop() {
				this.$axios('supgoods/goodsDel', 'POST', 'supplier', {
					id: this.id,
					uid: this.uid
				}).then(res => {
					if (res.data.code == 200) {
						this.$api.msg("删除成功");
						setTimeout(() => {
							this.$navBack();
						}, 500)
					}
				})
			},
			down() {
				this.$axios('supgoods/goodsDown', 'POST', 'supplier', {
					id: this.id,
					uid: this.uid
				}).then(res => {
					if (res.data.code == 200) {
						this.$api.msg("下架成功");
					}
				})
			},
			goodsUp() {
				this.$axios('supgoods/goodsUp', 'POST', 'supplier', {
					id: this.id,
					uid: this.uid
				}).then(res => {
					if (res.data.code == 200) {
						this.$api.msg("上架成功!");
					}
				})
			},
			getTypeList() {
				this.$axios('supgoods/cateList', "POST", 'supplier', {
					uid: this.uid
				}).then(res => {
					if (res.data.code == 200) {
						let data = res.data.data;
						this.typeList = data.map(v => {
							return {
								value: v.id,
								text: v.title
							}
						})
						if (this.id != -1) this.getInfo();
					}
				})
			},
			getInfo() {
				this.$axios('supgoods/goodsInfo', "POST", 'supplier', {
					id: this.id,
					uid: this.uid
				}).then(res => {
					if (res.data.code == 200) {
						let data = res.data.data;
						this.baseFormData = data;
						// this.baseFormData.img = {
						// 	"name": 'name',
						// 	"extname": 'extname',
						// 	"url": data.img,
						// }
					}
				})
			},
			submit(ref) {
				this.$refs[ref].validate().then(res => {
					let obj = {
						...this.baseFormData,
						img: this.baseFormData.img,
						labels: this.baseFormData.labels.filter(v => (v !== '')),
						uid: this.uid
					}
					this.$axios('supgoods/goodsSave', "POST", 'supplier', obj).then(res => {
						if (res.data.code == 200) {
							this.$api.msg('提交成功！');
							setTimeout(() => {
								this.$navBack();
							}, 500)
						}
					})
				}).catch(err => {
					console.log('err', err);
				})
			},
			deleteTap(v) {
				this.baseFormData.labels.splice(v, 1);
				this.key.splice(v, 1);
			},
			addLaber() {
				this.baseFormData.labels.push('');
				this.key.push(v4());
			}
		}
	}
</script>


<style lang="scss">
	.container {
		padding-bottom: 100upx;
	}
	.fill{
		width: 100%;
		height: 100%;
		position: fixed;
		top: 0;
		left: 0;
		background: rgba(#000,.8);
		z-index: 999999;
		display: flex;
		align-items: center;
		justify-content: center;
		.fill_item{
			width: 800rpx;
			height: 500rpx;
		}
	}

	.uni-forms {
		padding: 0 20upx;
	}

	.uni-forms .uni-forms-item {
		margin-top: 50upx;
		margin-bottom: 0;
	}

	.message {
		color: #999;
		font-size: 22upx;
	}
	.f_imgs{
		display: flex;
		flex-wrap: wrap;
		margin-right: -10rpx;
		.f_img{
			width: 220rpx;
			height: 220rpx;
			position: relative;
			margin: 20rpx 10rpx 0 0;
			image {
				height: 100%;
				width: 100%;
			}
			text{
				background: #999;
				border-radius: 50%;
				color: #fff;
				height: 50upx;
				line-height: 40upx;
				font-size: 40upx;
				position: absolute;
				top: -10upx;
				right: -10upx;
				text-align: center;
				width: 50upx;
				opacity: .8;
			}
		}
	}

	.buttons {
		margin-top: 70upx;
		display: flex;
		align-items: center;

		.go_submit {
			flex: 1;
			line-height: 80upx;
			margin-right: 20upx;
			box-shadow: 4rpx 5rpx 17rpx 7rpx #ddd;
		}

		.go_submit:last-child {
			margin: 0;
		}

	}


	.position {
		border: 1px #e5e5e5 solid;
		border-radius: 4px;
		color: #999;
		line-height: 35px;
		font-size: 12px;
		padding: 0 20upx;
	}
</style>